import { useTitle } from '@/hooks/web/use-title'
import { useNProgress } from '@/hooks/web/use-progress'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { usePageLoading } from '@/hooks/web/use-page-loading'
import { getToken, removeToken } from '@/utils/auth'
import { useSysStore } from '@/store/modules/system'

const permissionStore = usePermissionStoreWithOut()

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

const whiteList = ['/login'] // 不重定向白名单

export function createGuard(router) {
  // tslint:disable-next-line
  router.beforeEach(async (to, _from, next) => {
    start()
    loadStart()

    if (getToken()) {
      if (to.path === '/login') {
        next({ path: '/' })
      } else {
        if (permissionStore.getIsAddRouters) {
          next()
        } else {
          try {
            await useSysStore().afterLoginAction()
            next({ ...to, replace: true })
          } catch (error) {
            removeToken()
            next(`/login?redirect=${to.path}`)
          }
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      } else {
        next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      }
    }
  })

  router.afterEach((to) => {
    useTitle(to?.meta?.title as string)
    done() // 结束Progress
    loadDone()
  })
}
